In [1]:
# This tutorial will introduce simple implementations of for loops.
In [2]:
# Here's the simplest for loop.
for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9
In [3]:
# Note that the loop starts from i = 0 and has 10 iterations.  Therefore,
# the output is i = 1, 2, 3, ..., 9.  Also, Python will loop over only the lines
# following the 'for' statement that are indented.  Note the difference in the 
# outputs from the following two blocks of code.
In [4]:
# i**2 is in the loop:
print('i**2 is in the loop:')
for i in range(10):
    print(i)
    print(i**2)
i**2 is in the loop:
0
0
1
1
2
4
3
9
4
16
5
25
6
36
7
49
8
64
9
81
In [5]:
# i**2 is NOT in the loop:
print('\ni**2 is NOT in the loop:')
for i in range(10):
    print(i)
print(i**2)
i**2 is NOT in the loop:
0
1
2
3
4
5
6
7
8
9
81
In [6]:
# The loop can be made to increment in steps of two as follows:
import numpy as np
print('\nStep by two:')
for i in np.arange(0, 10, 2):
    print(i)
Step by two:
0
2
4
6
8
In [7]:
# Often, you may wish to perform calculations within a loop and then store
# the results of those calculations in a list.
In [8]:
# The first step is to create a list of x values that we will iterate over
x = np.arange(0, 1.9, 0.1)
print('x:', x)
x: [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8]
In [9]:
# Next, we will create an empty list that we will use to store the results
# of out calculation.
results = []
In [10]:
# We can now use our results list within a for loop and append values
# to list as the loop iterates.
umax = 0.54
M = -4.2703
D = 1.8
for i in x:
    results = results + [(umax/M)*np.log(1 + (np.exp(M)-1)*(i/D)*np.exp(1 - i/D))]
print('Results:',results)
Results: [-0.0, 0.019198493654414298, 0.03919043057194907, 0.060070244503352854, 0.08194889882372983, 0.1049575951738314, 0.1292523806498573, 0.15501976986589477, 0.18248332254542876, 0.21191058440110952, 0.24361834453296421, 0.27797032560786367, 0.31535137406103264, 0.3560759822264981, 0.4001223909632299, 0.44643492253916167, 0.49135988237282596, 0.526464135360927, 0.5400000000000005]
In [11]:
# In fact, we can now easiy plot results vs x.
import matplotlib.pyplot as plt
plt.plot(x, results, 'bo')
plt.xlabel('x');
plt.ylabel('results');
plt.axis((0, 1.8, 0, 0.6));